package game

import (
	"math"

	. "gddgame.cc/galaxy/common/dsl/game/ai"
	. "gddgame.cc/galaxy/common/dsl/game/ai_auto"
	. "gddgame.cc/galaxy/common/dsl/game/attr"
	"gddgame.cc/galaxy/common/dsl/game/badge"
	. "gddgame.cc/galaxy/common/dsl/game/object"
	"gddgame.cc/galaxy/common/service/playbook"
	"gddgame.cc/galaxy/project/star/star/model"
	"gddgame.cc/galaxy/utils"
)

func (center *Center) MakeCommand(id int, conditionId int) *AiCommandExt {
	return NewAiCommand(center.Commands[id], NewAiConditions(center.Conditions[conditionId]))
}

func (center *Center) GeneratePlayer(player *playbook.Player, user *model.User, index int) (*ObjectInfo, int) {
	// 根据用户信息，生成对象
	t := &ObjectInfo{
		Id:       index,
		Entity:   user.Entity,
		Name:     player.Open.NickName,
		Base:     center.Bases[user.BaseId],
		Category: 0,
		Identity: 1,
	}
	attr := AttrEffectSlice{}
	attrEvent := make([][]AttrEvent, 0)
	buffs := make([]int, 0)

	// 组队Buff加层
	if player.TeamNumber > 1 && model.TeamBuff > 0 {
		buffs = append(buffs, model.TeamBuff)
	}
	// 移除等级概念，获取基础等级信息
	//attr.MergeBase(model.LevelObjectAttrs[player.Level-1])
	attr = attr.MergeArray(model.LevelObjectAttrs[0], center.AttrData)
	t.Extend = &model.GamePlayerExtend{
		NickName: player.Open.NickName,
		Avatar:   player.Open.Avatar,
		Items:    make([]*model.NumberItem, len(user.Items)),
		Buffs:    buffs,
	}

	// 武器属性
	if user.Weapon > 0 {
		weapon := user.ItemMap[user.Weapon]
		weaponItem := center.Items[weapon.ItemId]
		weaponInside := weaponItem.Inside.(*model.ItemInside)
		if weapon.Durability > 0 {
			attr = attr.Merge(weaponInside.Attr)
		}
		t.Extend.(*model.GamePlayerExtend).Weapon = &model.BaseItem{
			Id:      weaponItem.Id,
			SkillId: weaponInside.Skill,
			Icon:    weaponItem.Icon,
		}
		attrEvent = append(attrEvent, weaponInside.AttrEvent...)
	}

	// 机甲属性
	if user.Machine > 0 {
		machine := user.ItemMap[user.Machine]
		machineItem := center.Items[machine.ItemId]
		machineInside := machineItem.Inside.(*model.ItemInside)
		if machine.Durability > 0 {
			attr = attr.Merge(machineInside.Attr)
		}
		t.Extend.(*model.GamePlayerExtend).Machine = &model.BaseItem{
			Id:      machineItem.Id,
			SkillId: machineInside.Skill,
			Icon:    machineItem.Icon,
		}
		attrEvent = append(attrEvent, machineInside.AttrEvent...)
	}

	// 道具属性
	for index, key := range user.Items {
		if key == 0 {
			continue
		}
		i, ok := user.ItemMap[key]
		if !ok {
			continue
		}
		item := center.Items[i.ItemId]
		itemInside := item.Inside.(*model.ItemInside)
		attr = attr.Merge(itemInside.Attr)
		t.Extend.(*model.GamePlayerExtend).Items[index] = &model.NumberItem{
			Id:        item.Id,
			SkillId:   itemInside.Skill,
			Number:    i.Number,
			IsConsume: item.IsConsume,
			Icon:      item.Icon,
		}
		attrEvent = append(attrEvent, itemInside.AttrEvent...)
	}
	// 徽章属性
	badgeAttr, badgeAttrEvent := center.BadgeAttrMerge(user.Badges)

	attr = attr.Merge(badgeAttr)
	t.Attr = attr.GenerateAttr()
	t.AttrEvent = append(attrEvent, badgeAttrEvent...)

	return t, attr.ComputeFightPower(center.SettingsAttrs)
}

func (center *Center) GenerateGroup(wr *utils.WeightRandom, number int32, power int, languages []string) [][]*ObjectInfo {
	list := make([][]*ObjectInfo, number)
	for i := int32(0); i < number; i++ {
		list[i] = center.GenerateAi(wr.Random().(int), power, false, languages)
	}
	return list
}

// power是战斗力
func (center *Center) GenerateAi(targetId int, power int, boss bool, languages []string) []*ObjectInfo {
	// 生成target
	extend := &GameAiExtend{
		IsBoss: boss,
	}
	var targetAi *ActorAi
	// 技能数为战斗力的位数：100=2个命令，1000=3个命令
	number := int(math.Log10(float64(power)))
	if boss {
		number += 2

		// Boss生成Ai
		configMap := center.AiConfig[targetId]
		aiList := make([]ModelAi, len(configMap))
		for aiMode, config := range configMap {
			ai := center.MakeAi(targetId, number, config)
			aiList[int(aiMode)] = ai
		}
		targetAi = MakeAi(aiList)
	}
	target := center.Targets[targetId]

	attr := AttrEffectSlice{}
	attr = attr.Merge(target.DefaultAttr)
	// 根据power生成对象属性
	attr.GenerateFightPower(center.SettingsAttrs, power, target.AttrRandom(center.SettingsAttrs))

	extend.Buffs = target.BuffRandom()
	extend.Skill = target.SkillRandom()
	// 生成多语言数据
	tt := make([]*ObjectInfo, len(languages))
	for index, language := range languages {
		t := center.MakeTarget(targetId, language)
		t.Attr = attr.GenerateAttr()
		t.Extend = extend
		if targetAi != nil {
			t.Ai = targetAi
		}
		tt[index] = &t
	}
	return tt
}

func (center *Center) MakeAi(targetId int, number int, config *AiGroupConfig) ModelAi {
	commandList := center.TargetCommands[targetId][config.AiMode]
	commands := make([]*AiCommandExt, 0, number+len(config.DefaultGroup))
	if commandList.Size() > 0 {
		for i := 0; i < number; i++ {
			key := commandList.Random().(int)
			conditions := center.CommandConditions[key]
			ii := utils.ToInt(conditions.Random())
			commands = append(commands, center.MakeCommand(key, ii))
		}
	}

	if defaultCommands, ok := center.DefaultCommand[targetId][config.AiMode]; ok {
		for _, group := range config.DefaultGroup {
			// 判断默认命令是否存在，添加
			if key, ok := defaultCommands[group]; ok && key > 0 {
				conditions := center.CommandConditions[key]
				conditionsId := utils.ToInt(conditions.Random())
				//fmt.Println(key, conditionsId)
				commands = append(commands, center.MakeCommand(key, conditionsId))
			}
		}
	}

	return MakeModelAi(commands, config)
}

func (center *Center) BadgeAttrMerge(badges map[int]*badge.UserBadge) (AttrEffectSlice, [][]AttrEvent) {
	attr := AttrEffectSlice{}
	attrEvent := make([][]AttrEvent, 0)
	// 徽章属性
	for key := range badges {
		tmp := center.Badges[key]
		if tmp.ParentId > 0 {
			badge := center.Badges[tmp.ParentId]
			badgeList := badge.Children()
			flag := false
			for _, child := range badgeList {
				if child.Id == key {
					continue
				}
				if _, ok := badges[child.Id]; ok {
					flag = true
					break
				}
			}
			if flag {
				continue
			}
		}
		inside := tmp.Inside.(*model.BadgeInside)
		attr = attr.Merge(inside.Attr)
		attrEvent = append(attrEvent, inside.AttrEvent...)
	}
	return attr, attrEvent
}
